<template>
  <div class="myContainer">
    <div class="panel">
      <el-row style="padding: 10px; border-bottom: 1px solid #dbdbdb">
        <el-col :span="24" class="myLineHeight_40px">
          {{title}}
          <el-radio-group 
            v-model="type" 
            size="mini" 
            style="margin-left: 10px;"
            @change="onChangeType">
            <el-radio-button label="全部终端" ></el-radio-button>
            <el-radio-button label="Android"></el-radio-button>
            <el-radio-button label="iOS"></el-radio-button>
          </el-radio-group>
          <a id="downlink"></a>
          <span class="updatetime">更新时间: {{updatetime}}</span>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8" class="myHeight_140">
          <h3>日登录用户</h3>
          <h2>
            <el-row :gutter="5">
              <el-col :span="12" style="text-align: right;">
                <b>{{day_load_user[1]}}</b>
              </el-col> 
              <el-col :span="12" style="text-align: left;">
                <span :style="'color:'+loadedriserateC" >{{loaded_rise_rate | loadedriserate}}</span>
              </el-col>
            </el-row>
          </h2>
          <h3>昨日: {{day_load_user[0]}}</h3>
        </el-col>
        <el-col :span="8" class="myBorderLR myHeight_140">
          <h3>日新增用户</h3>
          <h2>
            <el-row :gutter="5">
              <el-col :span="12" style="text-align: right;">
                <b>{{day_new_user[1]}}</b>
              </el-col> 
              <el-col :span="12" style="text-align: left;">
                <span :style="'color:'+newriserateC" >{{new_rise_rate | loadedriserate}}</span>
              </el-col> 
            </el-row>
          </h2>
          <h3>昨日: {{day_new_user[0]}}</h3>
        </el-col>
        <el-col :span="8" class="myHeight_140">
          <h3>累计登录用户</h3>
          <h2>
            <el-row :gutter="5">
              <el-col :span="12" style="text-align: right;">
                <b>{{cur_total_user[1]}}</b> 
              </el-col>
              <el-col :span="12" style="text-align: left;">
                <span :style="'color:'+totalriserateC" >{{total_rise_rate | loadedriserate}}</span>
              </el-col>
            </el-row>
          </h2>
          <h3>昨日: {{cur_total_user[0]}}</h3>
        </el-col>
      </el-row>
    </div>
    <div class="panel myMarginTop_10px">
      <el-row style="padding: 10px; border-bottom: 1px solid #dbdbdb">
        <el-col :span="10">
          <el-date-picker
            v-model="time"
            type="daterange"
            :clearable=false
            :editable=false
            align="left"
            size="small"
            unlink-panels
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="onChangeTime"
            :picker-options="timeOptions">
          </el-date-picker>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <vue-highcharts :options="visitorOptions" ref="visitorChart"></vue-highcharts>
        </el-col>
      </el-row>
      <el-row>
        <el-col class="more" v-if="open">
          <span @click="onOpen">展开详细数据</span>
          <i class="el-icon-arrow-down"></i>
        </el-col>
        <el-col style="padding: 0 10px" v-if="!open">
          <el-table
            ref="multipleTable"
            :data="tableData"
            :border = true
            :stripe = true
            v-loading="loading"
            style="width: 100%">
            <el-table-column
              prop="date_list"
              label="时间"
              >
            </el-table-column>
            <el-table-column
              prop="day_new_user"
              width="100"
              label="日新增用户"
              >             
            </el-table-column>          
            <el-table-column
              prop="day_load_user"
              width="100"
              label="日登录用户"
              >
            </el-table-column>         
            <el-table-column
              prop="last_7days_total"
              label="近7日登录"
              >
            </el-table-column>      
            <el-table-column
              prop="per_7days"
              label="日登录/近7日"
              >
            </el-table-column>      
            <el-table-column
              prop="last_30days_total"
              label="近30天登录"
              >
            </el-table-column>      
            <el-table-column
              prop="per_30days"
              width="120"
              label="日登录/近30天"
              >
            </el-table-column>      
            <el-table-column
              prop="cur_total_user"
              label="累计用户数量"
              >
            </el-table-column>
          </el-table>
        </el-col>
        <el-col class="more"  v-if="!open" style="margin-top: 10px">
          <span @click="onClose">收起详细数据</span>
          <i class="el-icon-arrow-up"></i>
        </el-col>
      </el-row>
    </div>
    <div class="panel myMarginTop_10px">
      <el-row style="padding: 10px; border-bottom: 1px solid #dbdbdb">
        业务模块使用情况
        <span class="updatetime">更新时间: {{updatetime2}}</span>
      </el-row>
      <el-row>
        <el-col :span="12" class="b bb br">
          <el-col :span="24" class="d">
            <i class="el-icon-tickets"></i>
            自助缴费
          </el-col>
          <el-col :span="8" class="c">
            当日缴费成功
            <p>{{day_succ}}</p>
          </el-col>
          <el-col :span="8" class="c">
            当日缴费失败
            <div>
              <span @click="onPayment">
                {{day_failed}}
                <i class="el-icon-info" style="color: #f00; font-size: 10px" v-if="showIcon"></i>
              </span>
            </div>
          </el-col>
          <el-col :span="8" class="c">
            月累计成功缴费
            <p>{{month_succ}}</p>
          </el-col>
        </el-col>
        <el-col :span="12" class="b bb">
          <el-col :span="24" class="d">
            <i class="el-icon-tickets"></i>
            访客邀请
          </el-col>
          <el-col :span="8" class="c">
            当日新增
            <p>{{visitor_day_added}}</p>
          </el-col>
          <el-col :span="8" class="c">
            人脸/新增
            <p>{{visitor_face_rate}}</p>
          </el-col>
          <el-col :span="8" class="c">
            月累计邀请
            <p>{{visitor_month_num}}</p>
          </el-col>
        </el-col>
        <el-col :span="12" class="b bb br">
          <el-col :span="24" class="d">
            <i class="el-icon-tickets"></i>
            维修申报
          </el-col>
          <el-col :span="8" class="c">
            当日新增
            <p>{{repair_day_added}}</p>
          </el-col>
          <el-col :span="8" class="c">
            当日完成
            <p>{{repair_day_complete}}</p>
          </el-col>
          <el-col :span="8" class="c">
            月累计上报
            <p>{{repair_month_report}}</p>
          </el-col>
        </el-col>
        <el-col :span="12" class="b bb">
          <el-col :span="24" class="d">
            <i class="el-icon-tickets"></i>
            投诉建议
          </el-col>
          <el-col :span="8" class="c">
            当日新增
            <p>{{complaint_day_added}}</p>
          </el-col>
          <el-col :span="8" class="c">
            当日完成
            <p>{{complaint_day_complete}}</p>
          </el-col>
          <el-col :span="8" class="c">
            月累计上报
            <p>{{complaint_month_report}}</p>
          </el-col>
        </el-col>
        <el-col :span="12" class="b br">
          <el-col :span="24" class="d">
            <i class="el-icon-tickets"></i>
            社区电商
          </el-col>
          <el-col :span="8" class="c">
            当日新增
            <p>-</p>
          </el-col>
          <el-col :span="8" class="c">
            当日有效
            <p>-</p>
          </el-col>
          <el-col :span="8" class="c">
            月累计产生
            <p>-</p>
          </el-col>
        </el-col>
      </el-row>
    </div>

    <el-dialog title="当日缴费失败人员清单" class="myBill" :visible.sync="myBill">
      <el-table
        ref="billTable"
        :data="billData"
        :border = true
        :stripe = true
        :loading="loadingDlg"
        style="width: 100%">
        <el-table-column
          type="index"
          label="序号"
          width="80"
          >
        </el-table-column>
        <el-table-column
          prop="failed_time"
          label="失败时间"
          >
        </el-table-column>
        <el-table-column
          prop="name"
          label="用户姓名"
          >             
        </el-table-column>          
        <el-table-column
          prop="phone"
          label="联系电话"
          >
        </el-table-column>      
        <el-table-column
          prop="room_info"
          label="房间信息"
          >
        </el-table-column>    
      </el-table>  
      <div class="block">                    
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page_num"
          :page-sizes="[10, 15]"
          :page-size="page_size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" class="myBgGreen" @click="onExport" :loading="loadingExport">导出Excel</el-button>
      </div> 
    </el-dialog>
  </div>
</template>

<style scoped>
  .myContainer{
    width: 1000px;
    margin:0 auto;
  }
  .panel{
    background: #fff;
  }
  .panel h2{
    font-weight:bold;
    padding: 5px 0;
  }
  .panel h2 b{
    font-weight: bold;
  }
  .panel h3{
    font-size: 14px;
  }
  .panel span{
    font-weight: normal;
    font-size: 12px;
  }
  .myTitleBorderBottom{
    color: #000;
    font-weight: 500;
    font-size: 16px;
    border-bottom: 1px solid #dbdbdb;
    padding: 0 10px;
  }
  .myBgGreen{
    background: #00c2a9;
    border-color: #00c2a9;
    color: #fff;
    margin-top:2px;
  }
  .myBgGreen:hover{
    background: #33ceba;
  }
  .myTextAlignRight{
    text-align: right;
  }
  .myLineHeight_40px{
    line-height: 40px;
  }
  .myMarginTop_10px{
    margin-top: 10px;
  }
  .updatetime{
    float: right;
    font-size: 12px;
  }
  .myBorderLR{
    border-left: 1px solid #dbdbdb;
    border-right: 1px solid #dbdbdb;
  }
  .myHeight_140{
    height: 100px;
    padding-top:15px; 
    text-align: center;
  }
  .more{
    text-align: center;
  }
  .more span{
    color: #409eff;
    cursor: pointer;
    line-height: 30px;
  }
  .b{
    padding: 10px;
  }
  .bb{
    border-bottom: 1px solid #dbdbdb;
  }
  .br{
    border-right: 1px solid #dbdbdb;
  }
  .c{
    text-align: center;
    font-size: 12px;
  }
  .c p,.c div{
    font-size: 16px;
    font-weight: bold;
    line-height: 30px;
  }
  .c span{
    font-size: 16px;
    font-weight: bold;
    cursor: pointer;
  }
  .d{
    padding-bottom: 10px;
  }
</style>

<script>
  import VueHighcharts from 'vue2-highcharts';
  import { getUserCount , getPayment , getRepair , getComplaint , getFaileduser , getVisitor } from '@/api/statisticalAnalysis';
  let XLSX = require('xlsx');
  export default {
    data(){
      return{  
        title:"运营统计数据", 
        type:"全部终端",   
        updatetime:(new Date()).toLocaleDateString() + " " + (new Date()).toLocaleTimeString(),
        updatetime2:(new Date()).toLocaleDateString() + " " + (new Date()).toLocaleTimeString(),
        tableData: [],
        open:true,
        time:[new Date(new Date().getTime() - 3600 * 1000 * 24 * 6),new Date()],
        timeOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 29);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        myBill:false,
        billData:[],

        total:null, //总条数  
        page_num: 1, //当前页码
        page_size: 10, //每页显示多少条 

        visitorOptions:{
          chart: {
            type: 'spline'
          },
          title: {
              text: ''
          },
          subtitle: {
              text: ''
          },
          xAxis: {
              type: 'category',
              categories: []
          },
          yAxis: {
              min: 0,
              title: {
                  text: '人(次)'
              }
          },
          legend: {
              enabled: true
          },
          credits:{
            enabled: false  
          },
          tooltip: {
              pointFormat: '<b>{point.y:.1f} 人(次)</b>'
          },
          series: []
        },
        day_new_user:[],
        day_load_user:[],
        cur_total_user:[],
        loaded_rise_rate:"",
        total_rise_rate:"",
        new_rise_rate:"",
        loadedriserateC:"#333",
        totalriserateC:"#333",
        newriserateC:"#333",
        day_succ:"-",
        day_failed:"-",
        month_succ:"-",
        showIcon:false,
        repair_day_added:"-",
        repair_day_complete:"-",
        repair_month_report:"-",
        complaint_day_added:"-",
        complaint_day_complete:"-",
        complaint_month_report:"-",
        loading:false,
        loadingDlg:false,
        loadingExport:false,
        visitor_day_added:"-",
        visitor_face_rate:"-",
        visitor_month_num:"-"
      }
    },
    created() {
      document.title=this.title;

      this.onGetUserCount();
      this.onGetUserCountTime(this.time[0],this.time[1]);

      this.onGetPayment();
      this.onGetRepair();
      this.onGetComplaint();
      this.getVisitor();
    },
    computed: {

    },
    components: {
      VueHighcharts 
    },
    filters: {
      loadedriserate(val){
        if(val<0){
          return `↓ ${val}%`;
        }else if(val>0){
          return `↑ ${val}%`;
        }else{
          return `--`;
        }
      }          
    },
    mounted () {
      this.outFile = document.getElementById('downlink');
    },
    methods:{
      onOpen(){
        this.open=false;
      },
      onClose(){
        this.open=true;
      },
      onPayment(){
        let vm=this;
        let params={
          sta_time:"",
          page_num: vm.page_num,
          page_size: vm.page_size
        }
        if(vm.day_failed<=0){
          return false;
        }
        vm.loadingDlg=true;
        getFaileduser(params).then(response => {
          let res=response.data;
          vm.billData=res.rows;
          vm.total = res.total;
          vm.loadingDlg=false;
          //console.log(res)
        }).catch(error => {
          vm.loadingDlg=false;
          console.log(error)
        })

        this.myBill=true;
      },
      handleSizeChange(val) {//每页条数控制
        this.page_size = val;
        this.onPayment();
      },
      handleCurrentChange(val) {//每页
        this.page_num = val;
        this.onPayment();
      },
      onGetUserCount(start='',end=''){
        let vm=this,subType="";
        if(vm.type=='全部终端'){
          subType=0;
        }else if(vm.type=='Android'){
          subType=1;
        }else if(vm.type=='iOS'){
          subType=2;
        }else if(vm.type=='wp'){
          subType=3;
        }else{
          subType=4;
        }
        let params={
          start:start,
          end:end,
          device_type:subType
        }
        getUserCount(params).then(response => {
          let res=response.data;
          vm.day_new_user=res.day_new_user;//日新增[昨日，今日]
          vm.day_load_user=res.day_load_user;//日登录[昨日，今日]
          vm.cur_total_user=res.cur_total_user;//当前累计[昨日，今日]
          vm.loaded_rise_rate=res.loaded_rise_rate;//登录人数增长率
          if(vm.loaded_rise_rate>0){
            vm.loadedriserateC="#f00";
          }else if(vm.loaded_rise_rate<0){
            vm.loadedriserateC="#409eff";
          }else{
            vm.loadedriserateC="#333";
          }
          vm.total_rise_rate=res.total_rise_rate;//总人数增长率
          if(vm.total_rise_rate>0){
            vm.totalriserateC="#f00";
          }else if(vm.total_rise_rate<0){
            vm.totalriserateC="#409eff";
          }else{
            vm.totalriserateC="#333";
          }
          vm.new_rise_rate=res.new_rise_rate;//新增人数增长率
          if(vm.new_rise_rate>0){
            vm.newriserateC="#f00";
          }else if(vm.new_rise_rate<0){
            vm.newriserateC="#409eff";
          }else{
            vm.newriserateC="#333";
          }
          vm.updatetime=(new Date()).toLocaleDateString() + " " + (new Date()).toLocaleTimeString();
        }).catch(error => {
        })
      },
      onGetUserCountTime(start,end){
        let vm=this,subType="";
        if(vm.type=='全部终端'){
          subType=0;
        }else if(vm.type=='Android'){
          subType=1;
        }else if(vm.type=='iOS'){
          subType=2;
        }else if(vm.type=='wp'){
          subType=3;
        }else{
          subType=4;
        }
        let params={
          start:start,
          end:end,
          device_type:subType
        }
        vm.loading=true;
        getUserCount(params).then(response => {
          let res=response.data;
          let date_list=res.date_list;
          let day_load_user=res.day_load_user;
          let day_new_user=res.day_new_user;
          let cur_total_user=res.cur_total_user;

          let last_7days_total=res.last_7days_total;
          let last_30days_total=res.last_30days_total;
          let per_7days=res.per_7days;
          let per_30days=res.per_30days;
          vm.tableData=[];
          for(let i=0; i<date_list.length; i++){
            vm.tableData.push({
              date_list:date_list[i],
              day_load_user:day_load_user[i],
              day_new_user:day_new_user[i],
              cur_total_user:cur_total_user[i],
              last_7days_total:last_7days_total[i],
              last_30days_total:last_30days_total[i],
              per_7days:per_7days[i],
              per_30days:per_30days[i]
            })
          }
          
          if(vm.$refs.visitorChart.getChart().series.length){
            for(let i=0; i<vm.$refs.visitorChart.getChart().series.length; ){
              vm.$refs.visitorChart.getChart().series[0].remove();
            }
          }
          vm.$refs.visitorChart.getChart().xAxis[0].setCategories(date_list);
          vm.$refs.visitorChart.getChart().addSeries(
            {
              name: '日登录用户',
              data: day_load_user,
              color: '#ffa92e',
              marker: {
                enabled: false
              }
            }
          )
          vm.$refs.visitorChart.getChart().addSeries(
            {
              name: '日新增用户',
              data: day_new_user,
              color: '#00c2a9',
              marker: {
                enabled: false
              }
            }
          )
          vm.$refs.visitorChart.getChart().addSeries(
            {
              name: '累计登录用户',
              data: cur_total_user,
              color: '#2eb3ff',
              marker: {
                enabled: false
              }
            }
          )
          vm.updatetime=(new Date()).toLocaleDateString() + " " + (new Date()).toLocaleTimeString();
          vm.loading=false;
        }).catch(error => {
          vm.loading=false;
          console.log(error)
        })
      },
      onChangeType(){
        let vm=this;
        vm.onGetUserCount();
        vm.onGetUserCountTime(vm.time[0],vm.time[1]);
      },
      onChangeTime(){
        let vm=this;
        vm.onGetUserCountTime(vm.time[0],vm.time[1]);
      },
      onGetPayment(){//自助缴费
        let vm=this;
        let params={
          sta_time:""
        }
        getPayment(params).then(response => {
          let res=response.data;
          vm.day_succ=res.day_succ;//当日成功
          vm.day_failed=res.day_failed;//当日失败
          vm.month_succ=res.month_succ;//累计成功
          if(vm.day_failed>0){
            vm.showIcon=true;
          }
        }).catch(error => {
          console.log(error)
        })
      },
      onGetRepair(){//维修申报
        let vm=this;
        let params={
          sta_time:""
        }
        getRepair(params).then(response => {
          let res=response.data;
          vm.repair_day_added=res.repair_day_added;//当日新增
          vm.repair_day_complete=res.repair_day_complete;//当日完成
          vm.repair_month_report=res.repair_month_report;//月累计上报
        }).catch(error => {
          console.log(error)
        })
      },
      onGetComplaint(){//投诉建议
        let vm=this;
        let params={
          sta_time:""
        }
        getComplaint(params).then(response => {
          let res=response.data;
          vm.complaint_day_added=res.complaint_day_added;//当日新增
          vm.complaint_day_complete=res.complaint_day_complete;//当日完成
          vm.complaint_month_report=res.complaint_month_report;//当月上报
        }).catch(error => {
          console.log(error)
        })
      },
      onExport(){
        let vm=this;
        let params={
          sta_time:"",
          page_num: vm.page_num,
          page_size: vm.total
        }
        vm.loadingExport=true;
        getFaileduser(params).then(response => {
          let res=response.data.rows;
          // console.log(res)
          vm.billData=res;
          if(res.length==0){
            vm.loadingExport=false;
            vm.$message.info("没有可导出的数据！");
            return;
          }
          let data = [{}],name="缴费失败人员信息";
          for (let k in res[0]) {
            data[0][k] = k
          }
          data = data.concat(res);
          vm.downloadExl(data, name);
          vm.loadingExport=false;
          vm.myBill=false;
          vm.$message.success(`导出成功！总共${res.length}条数据。`);
        }).catch(error => {
          vm.loadingExport=false;
          vm.$message.error("导出失败！");
          console.log(error)
        })
      },
      downloadExl: function (json, downName, type) {  // 导出到excel
        let keyMap = []
        for (let k in json[0]) {
          keyMap.push(k);
        }
        let tmpdata = [] 
        json.map((v, i) => keyMap.map((k, j) => Object.assign({}, {
          v: v[k],
          position: (j > 25 ? this.getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
        }))).reduce((prev, next) => prev.concat(next)).forEach(function (v) {
          tmpdata[v.position] = {
            v: v.v
          }
        })
        let outputPos = Object.keys(tmpdata)  
        let tmpWB = {
          SheetNames: ['缴费失败人员信息'], 
          Sheets: {
            '缴费失败人员信息': Object.assign({},
              tmpdata, 
              {
                '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] 
              })
          }
        }
        let tmpDown = new Blob([this.s2ab(XLSX.write(tmpWB,
          {bookType: (type === undefined ? 'xlsx' : type), bookSST: false, type: 'binary'} 
        ))], {
          type: ''
        }) 
        var href = URL.createObjectURL(tmpDown)  
        this.outFile.download = downName + '.xlsx'  
        this.outFile.href = href  
        this.outFile.click()  

        setTimeout(function () {  
          URL.revokeObjectURL(tmpDown) 
        }, 100)
      },
      s2ab: function (s) { 
        var buf = new ArrayBuffer(s.length)
        var view = new Uint8Array(buf)
        for (var i = 0; i !== s.length; ++i) {
          view[i] = s.charCodeAt(i) & 0xFF
        }
        return buf
      },
      getCharCol: function (n) { 
        let s = ''
        let m = 0
        while (n > 0) {
          m = n % 26 + 1
          s = String.fromCharCode(m + 64) + s
          n = (n - m) / 26
        }
        return s
      },
      getVisitor(){
        let vm=this;
        let params={
          sta_time:""
        }
        getVisitor(params).then(response => {
          let res=response.data;
          vm.visitor_day_added=res.visitor_day_added;//当日新增
          vm.visitor_face_rate=res.visitor_face_rate;//人脸/新增
          vm.visitor_month_num=res.visitor_month_num;//月累计邀请
          // console.log(res)
        }).catch(error => {
          console.log(error)
        })
      }
      
     
    }

  }


</script>



